﻿using BaseUI;
using BLL;
using Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.UI.WebControls;

namespace Thksoft.Funds
{
    public partial class PlanWeekFunds : BasePage
    {
        #region 重构代码

        private QS_PLANWEEKAPPLYBLL applyWeekBll = new QS_PLANWEEKAPPLYBLL();

        #endregion 重构代码

        private int Selectnum = -1;
        private static int isPB = 7;
        private static DataTable dtISPB = null;

        /// <summary>
        /// 判断是否首次加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("YearNum", Type.GetType("System.String"));
                dt.Columns.Add("Year", Type.GetType("System.String"));
                object[] parm = new object[2];
                int ye = Convert.ToInt32(DateTime.Now.AddYears(-5).Year.ToString());
                for (int i = ye; i <= Convert.ToInt32(DateTime.Now.AddYears(1).Year.ToString()); i++)
                {
                    parm[0] = i;
                    parm[1] = i + "";
                    dt.Rows.Add(parm);
                }
                DropDownList1.DataSource = dt;
                DropDownList1.DataValueField = "YearNum";
                DropDownList1.DataTextField = "Year";
                DropDownList1.DataBind();
                DropDownList1.SelectedValue = DateTime.Now.Year.ToString();

                DropDownList2.SelectedValue = DateTime.Now.Month.ToString();

                BindInit(DropDownList1.SelectedValue, DropDownList2.SelectedValue, DropDownList3.SelectedValue);
            }
        }

        /// <summary>
        /// 绑定加载数据
        /// </summary>
        public void BindInit(string year, string month, string week)
        {
            var result = applyWeekBll.CreateOrFind((int)lognUser.USER_ID, (int)lognUser.USER_COMPANY, Convert.ToInt32(year), Convert.ToInt32(month), Convert.ToInt32(week));
            if (result.Type != Utility.ResultType.success)
            {
                MessageBox.Show(this, result.Msg);
                return;
            }
            var entity = result.Data as QS_PLANWEEKAPPLY;
            HiddenField3.Value = entity.N_WEEKAPP_ID.ToString();
            //加载当前选取周的资金计划
            DataTable dt1 = applyWeekBll.GetDataSyBind(lognUser.USER_COMPANY.ToString(), lognUser.USER_COMPANY.ToString(), year, month, week, lognUser.USER_NAME);

            if (dt1 == null || dt1.Rows.Count == 0)
            {
                //本公司没有特殊项目，走通用项目
                dt1 = applyWeekBll.GetDataSyBind(lognUser.USER_COMPANY.ToString(), "0", year, month, week, lognUser.USER_NAME);
            }
            DataTable dt = CreatTable();
            for (int i = 0; i < dt1.Rows.Count; i++)
            {
                //
                if (dt1.Rows[i]["N_PARENTID"].ToString() == "0")
                {
                    var row = dt.NewRow();
                    row["n_proid"] = dt1.Rows[i]["n_proid"].ToString();
                    row["n_parentid"] = dt1.Rows[i]["n_parentid"].ToString();
                    row["c_proname"] = dt1.Rows[i]["c_proname"].ToString();
                    row["c_remark"] = dt1.Rows[i]["c_remark"].ToString();
                    row["n_type"] = dt1.Rows[i]["n_type"].ToString();
                    row["c_xm"] = "";
                    row["syjh"] = dt1.Rows[i]["syjh"].ToString();
                    row["mjeh"] = dt1.Rows[i]["mjeh"].ToString();
                    row["n_type1"] = dt1.Rows[i]["IF_DETAILS"].ToString();
                    row["c1"] = dt1.Rows[i]["DETAILS_CODE"].ToString();
                    dt.Rows.Add(row);
                    BindChild(dt, dt1, dt1.Rows[i]["n_proid"].ToString());
                }
            }

            gvMonthPlan.DataSource = dt;
            gvMonthPlan.DataBind();
        }

        /// <summary>
        /// 绑定子级
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="fid"></param>
        public void BindChild(DataTable dt, DataTable dt1, string fid)
        {
            for (int i = 0; i < dt1.Rows.Count; i++)
            {
                if (dt1.Rows[i]["n_parentid"].ToString() == fid)
                {
                    var row = dt.NewRow();
                    row["n_proid"] = dt1.Rows[i]["n_proid"].ToString();
                    row["n_parentid"] = dt1.Rows[i]["n_parentid"].ToString();
                    row["c_proname"] = dt1.Rows[i]["c_proname"].ToString();
                    row["c_remark"] = dt1.Rows[i]["c_remark"].ToString();
                    row["n_type"] = dt1.Rows[i]["n_type"].ToString();
                    row["c_xm"] = "";
                    row["syjh"] = dt1.Rows[i]["syjh"].ToString();
                    row["n_type1"] = dt1.Rows[i]["IF_DETAILS"].ToString();
                    row["c1"] = dt1.Rows[i]["DETAILS_CODE"].ToString();
                    row["mjeh"] = dt1.Rows[i]["mjeh"].ToString();
                    dt.Rows.Add(row);

                    BindChild(dt, dt1, dt1.Rows[i]["n_proid"].ToString());
                }
            }
        }

        public DataTable CreatTable()
        {
            DataTable _dt = new DataTable();
            _dt.Columns.Add("n_proid");
            _dt.Columns.Add("n_parentid");
            _dt.Columns.Add("c_proname");
            _dt.Columns.Add("c_remark");
            _dt.Columns.Add("n_type");
            _dt.Columns.Add("c_xm");
            _dt.Columns.Add("syjh");//本月累计资金计划
            _dt.Columns.Add("n_type1");
            _dt.Columns.Add("c1");

            _dt.Columns.Add("mjeh");//本月资金计划

            return _dt;
        }

        #region 添加行

        /// <summary>
        /// 添加行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            int k = 0;
            string father = "";
            string pids = "";
            if (p_id.Value.Trim().ToString() == "")
            {
                Response.Write("<script>alert('【系统提示】请将鼠标移至数据行操作！！！');</script>");
                return;
            }
            for (int i = 0; i < this.gvMonthPlan.Rows.Count; i++)
            {
                if (((Label)this.gvMonthPlan.Rows[i].FindControl("lblProID")).Text == p_id.Value.Trim())
                {
                    isPB = 0;
                    pids = ((Label)this.gvMonthPlan.Rows[i].FindControl("lblProID")).Text;
                    k = i + 1;
                    father = ((Label)this.gvMonthPlan.Rows[i].FindControl("lblProID")).Text;
                    break;
                }
            }

            if (pids.Equals(""))
            {
                isPB = 1;
                dtISPB = (DataTable)ViewState["ShowDataTable"];
                ViewState["ShowDataTable"] = dtISPB;
                Response.Write("<script>alert('【系统提示】请将鼠标移至数据行操作！！！');</script>");
                return;
            }

            Session["selectnum"] = k;
            // DataTable table = ReadGridView();

            //DataRow newRow = table.NewRow();
            ////newRow["pro_id"] = Guid.NewGuid().ToString();
            ////  table.Rows.Add(newRow);
            ////  newRow["pro_id"] = Guid.NewGuid().ToString();
            //table.Rows.InsertAt(newRow, k);

            DataTable dt = (DataTable)ViewState["tbCategory"];
            //Add new row
            DataColumn td = new DataColumn();

            DataRow dr = dt.NewRow(); //添加行

            dt.Rows.InsertAt(dr, k);
            string q = "";
            if (pids.Contains('.'))
            {
                father = father.Split('.')[0];
                q = pids.Split('.')[0];
            }
            else
            {
                q = pids;
            }
            decimal sh = Convert.ToDecimal(q) + 1;
            DataRow[] drw = dt.Select(" pro_id >= " + pids + " and pro_id < " + sh);
            decimal a = drw.AsEnumerable().Where(s => s.Field<object>("PRO_ID") != null && s.Field<object>("PRO_ID").ToString().Length > 0).Max(s => decimal.Parse(s.Field<object>("PRO_ID").ToString()));
            if (a.ToString().Contains("."))
            {
                int h = Convert.ToInt32(a.ToString().Split('.')[1].ToString());
                h += 1;
                pids = a.ToString().Split('.')[0].ToString() + "." + h;
            }
            else
            {
                pids = a + ".1";
            }

            dt.AcceptChanges();
            //得到最大值
            //        int a = dt.AsEnumerable().Where(s => s.Field<object>("PRO_ID") != null && s.Field<object>("PRO_ID").ToString().Length > 0).Max(s => int.Parse(s.Field<object>("PRO_ID").ToString()));

            dt.Rows[k][0] = pids;
            dt.Rows[k][5] = father;
            ViewState["ShowDataTable"] = dt;

            gvMonthPlan.DataSource = dt;

            gvMonthPlan.DataBind();

            // gvMonthPlan.Rows[k].Cells[2].Attributes["ondblclick"] = "showProject(\"" + pids + "_"+k+"\")";

            int ll = gvMonthPlan.Rows.Count;

            /*DropDownList dp = gvMonthPlan.Rows[k].FindControl("ddlName") as DropDownList;
            dt = new Qs_FundMonPlanBLL().SelctByMainID(Convert.ToDecimal(pids));
            dp.DataSource = dt;
            dp.DataTextField = "projectname";
            dp.DataValueField = "id";
            dp.DataBind();
            dp.Items.Insert(0, new ListItem("---请选择---", "-1"));

            dp.SelectedValue = "-1";
             dp.Visible = false;
             */

            ((Label)gvMonthPlan.Rows[k].FindControl("txtProjectName")).Visible = false;
            DataTable ff = (DataTable)gvMonthPlan.DataSource;

            Selectnum = k;
        }

        #endregion 添加行

        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnOk_Click(object sender, EventArgs e)
        {
            QS_PROJECTBLL probll = new QS_PROJECTBLL();

            string year = DropDownList1.SelectedValue;
            string month = DropDownList2.SelectedValue;
            string week = DropDownList3.SelectedValue;

            DateTime begData = DateTime.Now;
            DateTime endData = DateTime.Now;

            #region 数据验证

            if (!DateTime.TryParse(txtBeDate.Value, out begData))
            {
                MessageBox.Show(Page, "请选择周开始日期");
                return;
            }

            if (!DateTime.TryParse(txtEnd.Value, out endData))
            {
                MessageBox.Show(Page, "请选择周结束日期");
                return;
            }

            if (begData > endData)
            {
                MessageBox.Show(Page, "周开始日期不能小于结束日期");
                return;
            }

            if (txtremark.Text.Trim() == "")
            {
                MessageBox.Show(Page, "请输入编制依据");
                return;
            }

            string sqlMon = " and t.n_business_state=2 and  t.n_year=" + year + @" and t.n_month=" + month + @" and t.n_company_id= " + lognUser.USER_COMPANY.ToString();
            DataTable dtMon = new QS_PLANMONTHAPPLYBLL().GetSeleDataBind(sqlMon, lognUser.USER_NAME);
            if (dtMon != null && dtMon.Rows.Count > 0)
            {
            }
            else
            {
                MessageBox.Show(Page, year.ToString() + month.PadLeft(2, '0') + "月计划未申请或未归档！");
                return;
            }

            //判断重复提交
            DataTable dt2 = new QS_PLANWEEKAPPLYBLL().BindSelectBy(year, month, week, lognUser.USER_COMPANY.ToString(), 1, lognUser.USER_NAME);

            if (dt2 != null && dt2.Rows.Count > 0)
            {
                string state = dt2.Rows[0]["N_BUSINESS_STATE"].ToString();

                if (state == "1")
                {
                    MessageBox.Show(Page, "已申请当前周计划，流程正在流转中！");
                    return;
                }
                else if (state == "2")
                {
                    MessageBox.Show(Page, "已申请当前周计划，并且流程已归档！");
                    return;
                }
            }

            //判断在此周计划前，是否有周计划正在办理中
            DataTable dt = new QS_PLANWEEKAPPLYBLL().BindSelectBy(year, month, week, lognUser.USER_COMPANY.ToString(), 0, lognUser.USER_NAME);

            if (dt != null && dt.Rows.Count > 0)
            {
                MessageBox.Show(Page, year.ToString() + month.PadLeft(2, '0') + "月计划下有周计划正在办理中！");
                return;
            }

            #endregion 数据验证

            Sum();

            decimal bid = new Qs_BusinessBLL().GetYearDid("seq_business_id");

            string useWeek = year + month.PadLeft(2, '0') + week.PadLeft(2, '0');
            Sys_Company cModel = new Sys_CompanyBLL().GetInfoById(lognUser.USER_COMPANY.ToString());

            QS_Business bModel = new QS_Business();

            bModel.Business_Id = bid;
            bModel.Business_Name = year + "年" + month.PadLeft(2, '0') + "月" + "第" + week + "周计划编制（" + cModel.CMY_NAME + "）";

            Lc_Process proModel = new Lc_ProcessBLL().GetProcessByCom("QS_PLANWEEKAPPLY", lognUser.USER_NAME);

            if (proModel == null)
            {
                MessageBox.Show(Page, "未设置周计划流程！");
                return;
            }

            bModel.Process_id = proModel.N_PROCESS_ID;
            bModel.Business_State = 1;
            bModel.Business_operator_Id = int.Parse(lognUser.USER_ID.ToString());
            bModel.Business_remark = txtremark.Text.Trim();
            bModel.N_COMPANY_ID = lognUser.USER_COMPANY;

            QS_PLANWEEKAPPLY yModel = new QS_PLANWEEKAPPLY();
            yModel.N_WEEKAPP_ID = decimal.Parse(HiddenField3.Value);

            yModel.N_YEARAPP_ID = decimal.Parse(dtMon.Rows[0]["N_YEARAPP_ID"].ToString());
            yModel.N_MONTHAPP_ID = decimal.Parse(dtMon.Rows[0]["N_MONTHAPP_ID"].ToString());

            yModel.N_YEAR = decimal.Parse(year);
            yModel.N_MONTH = decimal.Parse(month);
            yModel.N_WEEK = decimal.Parse(week);

            yModel.C_USEWEEK = year + month.PadLeft(2, '0') + week.PadLeft(2, '0');

            yModel.N_BUSINESS_ID = bid;

            yModel.C_WEEK_NAME = bModel.Business_Name;

            yModel.N_COMPANY_ID = lognUser.USER_COMPANY;
            yModel.N_USER_ID = lognUser.USER_ID;
            yModel.C_REAMRK = txtremark.Text.Trim();
            yModel.N_BUSINESS_STATE = 1;

            yModel.D_START = begData;
            yModel.D_END = endData;

            // DataTable dt = (DataTable)gvMonthPlan.DataSource;

            List<QS_PLANWEEK_DETAIL> list = new List<QS_PLANWEEK_DETAIL>();
            for (int i = 0; i < gvMonthPlan.Rows.Count; i++)
            {
                QS_PLANWEEK_DETAIL ydModel = new QS_PLANWEEK_DETAIL();
                string type = ((Label)gvMonthPlan.Rows[i].Cells[0].FindControl("lbltype")).Text;
                string pid = ((Label)gvMonthPlan.Rows[i].Cells[0].FindControl("lblProID")).Text;
                string xmmc = ((Label)gvMonthPlan.Rows[i].Cells[1].FindControl("txtProjectName")).Text;
                string je = ((TextBox)gvMonthPlan.Rows[i].Cells[2].FindControl("txtNowMonth")).Text;

                QS_PROJECT jEctModel = probll.GetModelById(pid);

                string aa = "";
                //if (je != "" && je != null)
                //{
                //    aa = FormulaCalculator.Eval(je).ToString();
                //}
                //判断是否有汉字
                bool bl = System.Text.RegularExpressions.Regex.IsMatch(je, @"[\u4e00-\u9fa5]+$");
                if (je != "" && je != null)
                {
                    foreach (char c in je)
                    {
                        if (bl == false && char.IsLetter(c) == false)
                        {
                            //没有汉字也没有字母
                            aa = FormulaCalculator.Eval(je).ToString();
                        }
                        else
                        {
                            MessageBox.Show(this, "【温馨提示】资金计划列中输入格式不正确，请输入数字或算术表达式。如：23或1+1");
                            return;
                        }
                    }
                }

                string bz = ((TextBox)gvMonthPlan.Rows[i].Cells[3].FindControl("txtremark")).Text;

                string syje = ((Label)gvMonthPlan.Rows[i].Cells[2].FindControl("lblSyjh")).Text;

                string mjhje = ((Label)gvMonthPlan.Rows[i].Cells[2].FindControl("Label1")).Text;

                ydModel.N_WEEKAPP_ID = yModel.N_WEEKAPP_ID;

                ydModel.N_PROID = decimal.Parse(pid);
                ydModel.C_PRONAME = xmmc;

                ydModel.N_AMOUNT = aa == "" ? 0 : Convert.ToDecimal(aa);//decimal.Parse(aa);

                ydModel.C_REMARK = bz;
                ydModel.N_OPERATORID = lognUser.USER_ID;

                ydModel.N_BUSINESS_ID = bid;
                ydModel.N_TYPE = Convert.ToDecimal(type);//decimal.Parse(type);

                ydModel.N_SYAMOUNT = Convert.ToDecimal(syje);//decimal.Parse(syje);

                ydModel.N_MONTHAMOUNT = Convert.ToDecimal(mjhje);//decimal.Parse(mjhje);

                ydModel.N_USEAMOUNT = 0;

                ydModel.C_PROWEEKNUM = cModel.C_CODE + useWeek + pid.ToString();

                ydModel.C_PRONUM = jEctModel.C_PRONUM;
                ydModel.N_TYPE2 = jEctModel.N_TYPE2;
                ydModel.N_IF_DETAILS = jEctModel.N_IF_DETAILS;

                ydModel.C_DETAILS_CODE = jEctModel.C_DETAILS_CODE;
                ydModel.N_NUM1 = jEctModel.N_NUM1;

                ydModel.N_NUM2 = jEctModel.N_NUM2;
                ydModel.N_PARENTID = jEctModel.N_PARENTID;
                ydModel.N_AMOUNT1 = ydModel.N_AMOUNT;

                list.Add(ydModel);
            }

            Lc_Transaction tModel = new Lc_Transaction();
            tModel.N_PROCESS_ID = bModel.Process_id;

            //获取第一步队列id
            tModel.N_QUEUE_ID = new Lc_QueueBLL().QuByNumCom(bModel.Process_id, bModel.N_COMPANY_ID);//101;
            tModel.N_business_id = bid;
            tModel.N_TRANSACTION_STATE = 1;
            tModel.C_TRANSACTION_COMMENT = "周计划申请";
            tModel.C_TRANSACTOR_ID = lognUser.USER_ID.ToString();
            tModel.D_TRANSACTION_TIME_BEGIN = DateTime.Now;
            tModel.D_TRANSACTION_TIME_END = DateTime.Now;
            tModel.D_TRANSACTION_TIME_DUE = DateTime.Parse("1900-1-1");
            tModel.N_TRANSACTION_STATE = 1;

            tModel.C_TRANSACTOR_SIGNATURE = "";
            tModel.N_LAST_BACE_TRANSACTION_ID = 0;

            Lc_Transaction NexModel = new Lc_Transaction();
            NexModel.N_PROCESS_ID = bModel.Process_id;

            DataTable dtNex = new Lc_ConditionBLL().GetNextNum(bModel.Process_id, tModel.N_QUEUE_ID);
            if (dtNex == null || dtNex.Rows.Count == 0)
            {
                MessageBox.Show(Page, "未设置办理流水！");
                return;
            }

            NexModel.N_QUEUE_ID = decimal.Parse(dtNex.Rows[0][0].ToString()); //decimal.Parse(new Lc_ConditionBLL().GetNextNum(bModel.Process_id, tModel.N_QUEUE_ID).Rows[0][0].ToString());
            NexModel.N_business_id = bid;
            NexModel.N_TRANSACTION_STATE = 0;
            NexModel.C_TRANSACTION_COMMENT = "";
            NexModel.C_TRANSACTOR_ID = "";
            NexModel.D_TRANSACTION_TIME_BEGIN = DateTime.Now;
            NexModel.D_TRANSACTION_TIME_END = DateTime.Parse("1900-1-1");
            Lc_Queue qModel = new Lc_QueueBLL().GetInfoById(NexModel.N_QUEUE_ID.ToString());
            Lc_Node nModel = new Lc_NodeBLL().GetInfoById(qModel.N_NODE_ID.ToString());
            NexModel.D_TRANSACTION_TIME_DUE = DateTime.Now.AddDays(double.Parse(nModel.N_DOIING_TIME.ToString()));
            NexModel.N_TRANSACTION_STATE = 0;
            NexModel.C_TRANSACTOR_SIGNATURE = "";
            NexModel.N_LAST_BACE_TRANSACTION_ID = 0;

            int count = new QS_PLANWEEKAPPLYBLL().AppPlanWeek(bModel, yModel, list, tModel, NexModel, lognUser.USER_NAME);

            if (count > 0)
            {
                MessageBox.Show(Page, "申请成功！");
            }
            else
            {
                MessageBox.Show(Page, "申请失败！");
            }
        }

        protected void gvMonthPlan_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "cu=this.style.backgroundColor;this.style.backgroundColor='#d5e7ff'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=cu");

                ((CheckBox)this.gvMonthPlan.Rows[e.Row.RowIndex].FindControl("chkSelectDel")).Checked = true;
            }
        }

        protected void btnSum_Click(object sender, EventArgs e)
        {
            Sum();
        }

        #region 求和 方法

        /// <summary>
        /// 求和
        /// </summary>
        private void Sum()
        {
            #region for循环求和

            try
            {
                DataTable dt = (DataTable)gvMonthPlan.DataSource;

                for (int i = 0; i < gvMonthPlan.Rows.Count; i++)
                {
                    //0 主节点  1分节点  2子节点（可录入数据）
                    string type = ((Label)gvMonthPlan.Rows[i].Cells[1].FindControl("lbltype")).Text;
                    string pid = ((Label)gvMonthPlan.Rows[i].Cells[1].FindControl("lblProID")).Text;
                    if (type != "2")
                    {
                        //求和
                        decimal heje = 0;
                        //该节点下所有子节点
                        DataTable dtchild = new QS_PROJECTBLL().SelectFor(" and  d.n_type = 2 ", pid, lognUser.USER_NAME);

                        for (int j = 0; j < dtchild.Rows.Count; j++)
                        {
                            for (int k = 0; k < gvMonthPlan.Rows.Count; k++)
                            {
                                string type2 = ((Label)gvMonthPlan.Rows[k].Cells[1].FindControl("lbltype")).Text;

                                string pid2 = ((Label)gvMonthPlan.Rows[k].Cells[1].FindControl("lblProID")).Text;

                                //每个文本框求和
                                string je = ((TextBox)gvMonthPlan.Rows[k].Cells[2].FindControl("txtNowMonth")).Text.Trim();
                                string a = "";
                                //if (je != "" && je != null)
                                //{
                                //    a = FormulaCalculator.Eval(je).ToString();
                                //}
                                //判断是否有汉字
                                bool bl = System.Text.RegularExpressions.Regex.IsMatch(je, @"[\u4e00-\u9fa5]+$");
                                if (je != "" && je != null)
                                {
                                    foreach (char c in je)
                                    {
                                        if (bl == false && char.IsLetter(c) == false)
                                        {
                                            //没有汉字也没有字母
                                            a = FormulaCalculator.Eval(je).ToString();
                                        }
                                        else
                                        {
                                            MessageBox.Show(this, "【温馨提示】资金计划列中输入格式不正确，请输入数字或算术表达式。如：23或1+1");
                                            return;
                                        }
                                    }
                                }

                                if (type2 == "2" && dtchild.Rows[j]["n_proid"].ToString() == pid2)
                                {
                                    heje += Convert.ToDecimal(a == "" ? "0" : a);
                                    //heje += Convert.ToDecimal(((TextBox)gvMonthPlan.Rows[k].Cells[2].FindControl("txtNowMonth")).Text.Trim() == "" ? "0" : ((TextBox)gvMonthPlan.Rows[k].Cells[2].FindControl("txtNowMonth")).Text.Trim());
                                }
                            }
                        }

                        ((Label)gvMonthPlan.Rows[i].Cells[2].FindControl("lblMonthjh")).Text = heje.ToString();
                        ((TextBox)gvMonthPlan.Rows[i].Cells[2].FindControl("txtNowMonth")).Text = heje.ToString();
                    }
                    else
                    {
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Page, ex.Message);
                return;
            }

            #endregion for循环求和
        }

        #endregion 求和 方法

        protected void gvMonthPlan_RowDataBound1(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string sss = ((Label)e.Row.FindControl("lblProID")).Text;
                e.Row.Attributes.Add("onmouseover", "document.getElementById(\"p_id\").value=\"\"");
                e.Row.Attributes.Add("onmouseout", "document.getElementById(\"p_id\").value=\"" + ((Label)e.Row.FindControl("lblProID")).Text + "\";");
                e.Row.Cells[2].Attributes["style"] = "cursor:hand";
                string s = ((Label)e.Row.FindControl("lblFatherId")).Text;
                //  e.Row.Cells[2].Attributes["ondblclick"] = "showProject(\"" + s + "_" + e.Row.RowIndex + "\")";
                e.Row.Cells[2].Attributes["onContextMenu"] = "YouJian()";
                e.Row.Cells[1].Attributes["onContextMenu"] = "YouJian()";

                string type = ((Label)e.Row.FindControl("lbltype")).Text;
                var ifdetails = ((HiddenField)e.Row.FindControl("HiddenField1")).Value == "1" ? true : false;
                if (type == "2")
                {
                    //查询详情表的值
                    var applyId = Convert.ToInt32(HiddenField3.Value);

                    decimal je = applyWeekBll.GetMoneyByDetails(applyId, Convert.ToInt32(sss));
                    if (ifdetails)
                    {
                        if (je > 0)
                        {
                            ((TextBox)e.Row.FindControl("txtNowMonth")).Text = je.ToString();
                        }
                        else
                        {
                            //  ((TextBox)e.Row.FindControl("txtNowMonth")).Text = "0";
                        }

                        var code = ((HiddenField)e.Row.FindControl("HiddenField2")).Value;
                        ((TextBox)e.Row.FindControl("txtNowMonth")).Attributes.Add("onclick", "app1.ToDetails(" + HiddenField3.Value + ",3," + sss + ",'" + code + "')");
                        ((TextBox)e.Row.FindControl("txtNowMonth")).ReadOnly = true;
                    }
                    else
                    {
                        ((TextBox)e.Row.FindControl("txtNowMonth")).Text = "0";
                    }
                }
                if (type == "0")
                {
                    e.Row.Attributes["style"] = "background-color:#B2D8FF;font-size:14px";
                    ((TextBox)e.Row.FindControl("txtNowMonth")).Visible = false;
                    ((TextBox)e.Row.FindControl("txtNowMonth")).Enabled = false;
                    ((Label)e.Row.FindControl("lblMonthjh")).Visible = true;

                    ((TextBox)e.Row.FindControl("txtremark")).Visible = false;
                    ((Label)e.Row.FindControl("lblreMark")).Visible = true;

                    // e.Row.Cells[2].Attributes["style"] = "font-size: 14px";
                }
                else if (type == "1")
                {
                    e.Row.Attributes["style"] = "background-color:#CCCCCC;font-size:13px";
                    ((TextBox)e.Row.FindControl("txtNowMonth")).Visible = false;
                    ((TextBox)e.Row.FindControl("txtNowMonth")).Enabled = false;
                    ((Label)e.Row.FindControl("lblMonthjh")).Visible = true;

                    ((TextBox)e.Row.FindControl("txtremark")).Visible = false;
                    ((Label)e.Row.FindControl("lblreMark")).Visible = true;
                    // e.Row.Cells[2].Attributes["style"] = "font-size: 13px";
                }
            }
        }

        protected void gvMonthPlan_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (Session["selectnum"] != null && Session["selectnum"].ToString() != "")
            //{
            //    Selectnum = int.Parse(Session["selectnum"].ToString());
            //}
            //if (Selectnum != -1 && Selectnum != gvMonthPlan.SelectedIndex)
            //{
            //    DataTable ff = (DataTable)gvMonthPlan.DataSource;
            //    DropDownList dt = gvMonthPlan.Rows[Selectnum].FindControl("ddlName") as DropDownList;
            //    Label lab = ((Label)gvMonthPlan.Rows[Selectnum].FindControl("lblProjectName")) as Label;
            //    if (dt != null)
            //    {
            //        if (lab != null)
            //        {
            //            lab.Text = dt.SelectedValue;
            //        }
            //        Label lab1 = ((Label)gvMonthPlan.Rows[Selectnum].FindControl("txtProjectName")) as Label;
            //        if (lab1 != null)
            //        {
            //            lab1.Text = dt.SelectedValue;
            //            lab1.Visible = true;
            //        }
            //        dt.Visible = false;
            //    }
            //}
        }

        protected void gvMonthPlan_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            //Response.Write("<script>alert('" + e.NewSelectedIndex + "')</script>");
            //if (Session["selectnum"] != null && Session["selectnum"].ToString() != "")
            //{
            //    Selectnum = int.Parse(Session["selectnum"].ToString());
            //}
            //if (Selectnum != -1 && Selectnum == e.NewSelectedIndex)
            //{
            //    DropDownList dp = gvMonthPlan.Rows[e.NewSelectedIndex].FindControl("ddlName") as DropDownList;
            //    if (dp != null)
            //    {
            //        AddStr = dp.Text;
            //        Addid = dp.SelectedValue.ToString();
            //    }
            //}
        }

        protected void btnAsk_Click(object sender, EventArgs e)
        {
            //  Save(2);
        }

        #region 删除行

        /// <summary>
        /// 删除行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDel_Click(object sender, EventArgs e)
        {
            int k = 0;
            string father = "";
            string pids = "";
            if (p_id.Value.Trim().ToString() == "")
            {
                Response.Write("<script>alert('【系统提示】请将鼠标移至数据行操作！！！');</script>");
                return;
            }
            for (int i = 0; i < this.gvMonthPlan.Rows.Count; i++)
            {
                if (((Label)this.gvMonthPlan.Rows[i].FindControl("lblProID")).Text == p_id.Value.Trim())
                {
                    //0 主节点  1分节点  2子节点（可录入数据）
                    string type = ((Label)gvMonthPlan.Rows[i].Cells[0].FindControl("lbltype")).Text;
                    if (type != "2")
                    {
                        return;
                    }

                    isPB = 0;
                    pids = ((Label)this.gvMonthPlan.Rows[i].FindControl("lblProID")).Text;
                    k = i;
                    father = ((Label)this.gvMonthPlan.Rows[i].FindControl("lblProID")).Text;
                    break;
                }
            }

            DataTable dt = (DataTable)ViewState["MPlanDataTable"];// (DataTable)ViewState["tbCategory"];
            dt.Rows.Remove(dt.Rows[k]);

            gvMonthPlan.DataSource = dt;
            gvMonthPlan.DataBind();

            ViewState["MPlanDataTable"] = dt;
        }

        #endregion 删除行

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string year = DropDownList1.SelectedValue;

            string month = DropDownList2.SelectedValue;
            BindInit(year, month, DropDownList3.SelectedValue);
        }

        protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
        {
            string year = DropDownList1.SelectedValue;

            string month = DropDownList2.SelectedValue;

            BindInit(year, month, DropDownList3.SelectedValue);
        }

        protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
        {
            string year = DropDownList1.SelectedValue;

            string month = DropDownList2.SelectedValue;

            BindInit(year, month, DropDownList3.SelectedValue);
        }

        /// <summary>
        /// 重新加载数据(子表信息)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ReLoadClick(object sender, EventArgs e)
        {
            foreach (GridViewRow row in gvMonthPlan.Rows)
            {
                string proId = ((Label)row.FindControl("lblProID")).Text;
                string type = ((Label)row.FindControl("lbltype")).Text;
                var ifdetails = ((HiddenField)row.FindControl("HiddenField1")).Value == "1" ? true : false;
                if (type == "2" && ifdetails)
                {
                    //查询详情表的值
                    var applyId = Convert.ToInt32(HiddenField3.Value);
                    decimal je = applyWeekBll.GetMoneyByDetails(applyId, Convert.ToInt32(proId));

                    if (je > 0)
                    {
                        ((TextBox)row.FindControl("txtNowMonth")).Text = je.ToString();
                    }
                    else
                    {
                        //  ((TextBox)e.Row.FindControl("txtNowMonth")).Text = "0";
                    }

                    var code = ((HiddenField)row.FindControl("HiddenField2")).Value;
                    ((TextBox)row.FindControl("txtNowMonth")).Attributes["onclick"] = "app1.ToDetails(" + HiddenField3.Value + ",3," + proId + ",'" + code + "')";
                    ((TextBox)row.FindControl("txtNowMonth")).ReadOnly = true;
                }
            }
        }
    }
}